<template>
  <!-- 公告信息区域 -->
  <div class="announcement">
    <!-- 左侧固定公告图标区域 -->
    <div class="announcement__left">
      <span>公告</span>
      <i class="fas fa-bullhorn" />
    </div>

    <!-- 右侧滚动内容区域 -->
    <div class="announcement__right">
      <div
        ref="contentWrapper"
        class="announcement__content"
        :class="{ 'is-animating': isAnimating }"
      >
        <div
          ref="currentItem"
          class="announcement__item"
          :style="{ transform: `translateX(${currentPosition}px)` }"
        >
          {{ currentNotice.content }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Announcement',
  props: {
    notice: {
      type: Array,
      default: () => [],
      required: true
    }
  },
  data() {
    return {
      currentIndex: 0, // 当前显示的公告索引
      currentPosition: 0, // 文字滚动位置
      isAnimating: false, // 是否在切换动画中
      animationFrame: null, // 动画帧ID
      scrollTimer: null, // 滚动计时器
      pauseTimer: null, // 暂停计时器
      delayTimer: null // 新增延迟定时器
    }
  },
  computed: {
    currentNotice() {
      return this.notice[this.currentIndex] || { content: '' }
    }
  },
  watch: {
    // 监听公告数据变化，重新开始滚动
    notice: {
      deep: true,
      handler() {
        if (this.notice.length > 0) {
          this.currentIndex = 0
          this.clearTimers()
          this.startScroll()
        }
      }
    }
  },
  mounted() {
    if (this.notice.length > 0) {
      this.startScroll()
    }
  },
  beforeDestroy() { // Vue 2 中使用 beforeDestroy 替代 beforeUnmount
    // 清理定时器和动画帧
    this.clearTimers()
  },
  methods: {
    // 开始滚动当前公告
    startScroll() {
      // 清除现有定时器
      this.clearTimers()

      this.$nextTick(() => {
        const itemEl = this.$refs.currentItem
        const wrapperEl = this.$refs.contentWrapper

        if (!itemEl || !wrapperEl) return

        // 重置位置（关键：无论是否滚动，先重置到初始位置）
        this.currentPosition = 0

        // 计算内容宽度和容器宽度
        const contentWidth = itemEl.offsetWidth
        const wrapperWidth = wrapperEl.offsetWidth
        const needScroll = contentWidth > wrapperWidth

        // 短内容：立即显示，不延迟
        if (!needScroll) {
          this.pauseAndNext()
          return
        }

        // 长内容：延迟1秒后滚动（保留原逻辑）
        this.delayTimer = setTimeout(() => {
          // 计算滚动参数
          const scrollDistance = contentWidth - wrapperWidth
          const scrollSpeed = 75 // 每秒滚动像素数
          const scrollTime = scrollDistance / scrollSpeed * 1000
          const frameDuration = 16
          const pixelsPerFrame = scrollDistance / (scrollTime / frameDuration)

          // 开始滚动动画
          const scroll = () => {
            this.currentPosition -= pixelsPerFrame
            if (Math.abs(this.currentPosition) >= scrollDistance) {
              this.currentPosition = -scrollDistance
              this.pauseAndNext()
              return
            }
            this.animationFrame = requestAnimationFrame(scroll)
          }

          this.animationFrame = requestAnimationFrame(scroll)
        }, 1000) // 仅长内容延迟1秒
      })
    },

    // 暂停并准备显示下一条
    pauseAndNext() {
      // 暂停3秒后切换到下一条
      this.pauseTimer = setTimeout(() => {
        this.switchToNext()
      }, 5000)
    },

    // 切换到下一条公告
    switchToNext() {
      this.isAnimating = true

      // 上移动画时间与CSS动画保持一致
      setTimeout(() => {
        // 更新索引
        this.currentIndex = (this.currentIndex + 1) % this.notice.length
        // 重置动画状态
        this.isAnimating = false
        // 开始新公告的滚动
        this.startScroll()
      }, 500)
    },

    // 清除所有定时器和动画帧
    clearTimers() {
      if (this.animationFrame) {
        cancelAnimationFrame(this.animationFrame)
      }
      if (this.scrollTimer) {
        clearTimeout(this.scrollTimer)
      }
      if (this.pauseTimer) {
        clearTimeout(this.pauseTimer)
      }
    }
  }
}
</script>
<style scoped>
.announcement {
  * {
    user-select: none;
    cursor: pointer;
  }

  padding: 15px 20px;
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(8, 8, 8, 0.15);
  display: flex;
  align-items: center;
  width: 100%;
  box-sizing: border-box;
  background: #fff;
}

/* 左侧固定区域 */
.announcement__left {
  display: flex;
  align-items: center;
  gap: 8px;
  padding-right: 16px;
  margin-right: 16px;
  border-right: 1px solid #eee;
  color: #e63946; /* 深一点的红色，更正式 */
  font-weight: 500; /* 中等字重，突出标题 */
  white-space: nowrap;
  font-size: 14px;
}

.announcement__left i {
  font-size: 16px;
  opacity: 0.9; /* 图标稍淡，避免抢镜 */
}

/* 右侧滚动区域 */
.announcement__right {
  flex: 1;
  overflow: hidden;
  position: relative;
  height: 26px; /* 略微增高，提升行高舒适度 */
}

.announcement__content {
  position: absolute;
  width: 100%;
  height: 100%;
  transition: transform 0.5s ease-in-out, opacity 0.5s ease-in-out;
}

/* 切换动画 */
.announcement__content.is-animating {
  transform: translateY(-100%);
  opacity: 0;
}

/* 公告内容项 - 核心文字样式优化 */
.announcement__item {
  white-space: nowrap;
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  line-height: 26px; /* 与容器高度一致，垂直居中更自然 */
  transition: transform 0s linear;
  color: #333; /* 深灰色，比纯黑柔和，减少视觉疲劳 */
  font-size: 14px;
  letter-spacing: 0.3px; /* 微调字间距，提升可读性 */
  text-shadow: 0 0 1px rgba(0, 0, 0, 0.05); /* 极淡阴影，增加文字层次感 */
  font-weight: 400; /* 常规字重，适合长文本阅读 */
}

/* 鼠标悬停时轻微加深颜色，提升交互感 */
.announcement:hover .announcement__item {
  color: #222;
  transition: color 0.3s ease;
}
</style>
